#include "director.h"
#include "map_manager.h"
#include "camera.h"

using namespace alice;

Director* Director::instance_ = nullptr;
People* people = nullptr;

bool Director::Init() {
  if (SDL_Init(SDL_INIT_VIDEO != 0) && IMG_Init(IMG_INIT_JPG | IMG_INIT_PNG) != 0) {
    SDL_Log("Failed to initialize SDL: %s\n", SDL_GetError());
    return false;
  }

  SDL_WindowFlags window_flags = (SDL_WindowFlags) (SDL_WINDOW_RESIZABLE | SDL_WINDOW_ALLOW_HIGHDPI);
  window_ = SDL_CreateWindow(kWindowTitle, SDL_WINDOWPOS_CENTERED, SDL_WINDOWPOS_CENTERED, kWindowWidth, kWindowHeight, window_flags);
  if (window_ == nullptr) {
    SDL_Log("Failed to create Window: %s\n", SDL_GetError());
    return false;
  }

  renderer_ = SDL_CreateRenderer(window_, -1, SDL_RENDERER_ACCELERATED | SDL_RENDERER_PRESENTVSYNC);
  if (renderer_ == nullptr) {
    SDL_Log("Failed to create Renderer: %s\n", SDL_GetError());
    return false;
  }

  // 测试区域
  if (!MapManager::GetInstance()->Load()) {
    SDL_Log("Failed to load map\n");
  }
  level_map_ = MapManager::GetInstance()->GetMap("level-1");
  TextureManager::GetInstance()->Load("spr-idle", Tool::CurrentPath() + "/res/characters/spr/" + "spr_Idle_strip.png");
  TextureManager::GetInstance()->Load("spr-attack", Tool::CurrentPath() + "/res/characters/spr/" + "spr_Attack_strip.png");
  TextureManager::GetInstance()->Load("spr-walk", Tool::CurrentPath() + "/res/characters/spr/" + "spr_Walk_strip.png");
  TextureManager::GetInstance()->Load("spr-jump", Tool::CurrentPath() + "/res/characters/spr/" + "spr_Jump_strip.png");
  people = new People(new Properties("spr-idle", 0, 400, 170, 96));
  Camera::GetInstance()->SetTarget(people->GetOrigin());
  return is_running_ = true;
}

void Director::Clean() {
  TextureManager::GetInstance()->Clean();
  MapManager::GetInstance()->Clean();
  SDL_DestroyWindow(window_);
  SDL_DestroyRenderer(renderer_);
  IMG_Quit();
  SDL_Quit();
  delete instance_;
}

void Director::Quit(){
  is_running_ = false;
}

void Director::Events() {
  EventsManager::GetInstance()->Listen();
}

void Director::Update() {
  double delta_time = Timer::GetInstance()->GetDeltaTime();
  level_map_->Update();
  people->Update(delta_time);
  Camera::GetInstance()->Update(delta_time);
}

void Director::Render() {
  SDL_SetRenderDrawColor(renderer_, 24, 24, 24, 255);
  SDL_RenderClear(renderer_);

  level_map_->Render();
  people->Draw();

  SDL_RenderPresent(renderer_);
}

